function department_add(){
	var departmentName=$('#txtDepartmentName').val();
	var levelCity=$('#department_shi_administration').val();
	var levelTown=$('#department_xian_administration').val();
    var regionCode = whatTheRegionCode(levelCity,levelTown);
    
	var url='department_add_regioncode.shtml';
	url+='?name='+departmentName+'&code='+regionCode;
	$.get(encodeURI(url),function(data){
					  if(data==='true'){
						  $("#txtDepartmentName").val("");
						  alert("添加成功");
					  }else{
						  alert("添加失败");
					  };
			});
}

function whatTheRegionCode(levelCity,levelTown){
    if(levelTown == "-1"){
    	if(levelCity == "-1"){
			return "420000";
    	}
    	else{
    		return levelCity;
    	}
	}
	return levelTown;
}

// $("#rfReadTable").flexOptions(option).flexReload();
				  
function getInitData(){
	var url='department_query.shtml';
	var rp = 10;
	var page =1;
	url+="?rp="+rp+"&page="+page;
//	url+='?name='+departmentName+'&category='+departmentCate;
	$.get(encodeURI(url),function(data){	  
						  return data;
			});
}

function initDepartment_Query(){
	var department_cols =  [
	                        {display: '编号', name : 'id', width : 50, sortable : true, align: 'center',hide: false,toggle : false},
	            			 {display: '部门名称', name : 'department_name', width : 200, sortable : false, align: 'center'},
//	            			 {display: '类型', name : 'department_category', width : 100, sortable : true, align: 'center'},
	            			 {display: '备注', name : 'department_remarks', width : 250, sortable : true, align: 'center'}
	            		     ];

	var department_buttons =   [
	           				 			{ name: '更新', displayname: '更新', bclass: 'modify', onpress: onDepartmentUpdate },
	           				 			{separator: true},
	           				 			{ name: '删除',displayname: '删除', bclass: 'delete', onpress: onDepartmentDelete }
	           				 			];
	var setting={
		   width: 930,
		   height: 220,
		   url: 'department_query.shtml',
		   dataType: 'json',
		   colModel :department_cols,
			buttons:department_buttons,
			searchitems : [
			  {display: '编号', name : 'id', isdefault: true},
			  {display: '部门名称', name : 'department_name'}
//			  {display: '类型', name : 'department_category'},
			],
			preProcess:onDepartmentPreProcess,
			errormsg: '发生异常',
			sortname: "id",
			sortorder: "desc",
			usepager: true,
			title: '部门纪录',
			pagestat: '显示记录从{from}到{to}，总数{total}条',
			useRp: true, 
			rp: 10, 
			rpOptions: [10, 15, 20, 30, 40, 100],
			nomsg: '没有符合条件的记录存在',
			minColToggle: 1, 
			showTableToggleBtn: false, 
			autoload: false,
			resizable: false, 
			pagetext: '页',
         outof: '共',
         findtext: '查找',
         pagestat: "当前显示记录{from}到{to}条，总{total}条",
			procmsg: '加载中, 请稍等 ...', 
			singleSelect:true
		  };
	var grid=$("#departmentTable").flexigrid(setting);
	$("#departmentTable").flexOptions(setting).flexReload();
};

function onDepartmentDelete(com,grid){
	    var selected_count = $('.trSelected', grid).length;
	 
	    if (selected_count != 1) {
	        alert("请选择一条记录！");
	        return;
	    }
	    else {
	    	var isDelete = confirm("你确定要删除这条记录吗？");
	    	if(!isDelete){
	    		return;
	    	}
	        var department_id = parseInt($(".trSelected td>div", grid)[0].textContent);
	        var url = encodeURI("department_delete.shtml?department_id="+department_id);
	        $.get(url,function(data){
	        	if(data=="true"){
	        		alert("删除成功！");
	        		initDepartment_Query();
	        	}
	        	else{
	        		alert("删除失败！");
	        	}
	        });
	    }
}

function onDepartmentUpdate(com, grid){
    var data = {};
    var selected_count = $('.trSelected', grid).length;
 
    if (selected_count != 1) {
        alert("请选择一条记录！");
        return;
    }
    else {
        data.id = parseInt($(".trSelected td>div", grid)[0].textContent);
        data.department_name= $("#department_query_name").val();
        
        var cityRegionCode = $("#department_query_shi_admini").val();
        var townRegionCode = $("#department_query_xian_admini").val();
        var finalRegionCode = whatTheRegionCode(cityRegionCode,townRegionCode);
        data.department_regionCode = finalRegionCode;
        
        //data.department_category = $(".trSelected td>div", grid)[2].textContent;
        data.department_remarks = $(".trSelected td>div", grid)[2].children[0].value;
        $.post("department_update.shtml",{"data":JSON.stringify(data)},function(data){
        	if(data=="true"){
        		alert("更新成功");
        		$('#department_citytown_change').hide();
        		initDepartment_Query();
        	}
        	else{
        		alert("更新失败");
        	}
        });
    }
}

function changeDepartment(regionCode,departmentName,departmentId){
	$('#department_citytown_change').show();
	$('#selectedDepartmentId').val(departmentId);
	$('#department_query_name').val(departmentName);
	var lastTwoRegionCode = regionCode.substring(4,6);
	var middleTwoRegionCode = regionCode.substring(2,4);
	var cityRegionCode = regionCode.substring(0,4)+"00";
	setOption("420000",'department_query_shi_admini');
	setSltDefaultVal('department_query_shi_admini',cityRegionCode);
	if(lastTwoRegionCode != "00"){
		changeShiItem(cityRegionCode,"department_query_xian_admini");
		setSltDefaultVal('department_query_xian_admini',regionCode);
	}
	else{
		$("#department_query_xian_admini").val("-1");
	}
}

function onDepartmentPreProcess(data){
    var newData;
    var m = (data.page - 1) * 10 + 1;
    if (data != null) {
        var rows = [];
        for (var i = 0; i < data.rows.length; i++) {
            var cellContent = [];
            cellContent.push("<div style='height:10px;'>" + data.rows[i].cell.id + "</div>");
            
            var departmentRegionCode = data.rows[i].cell.department_regionCode;
            var departmentName = data.rows[i].cell.department_name;
            var departmentId = data.rows[i].cell.id;
            
            var departmentChangeBtn ="<input type='button' value='"+departmentName+ "'"+
            " style='width:150px;height:26px;font-family:微软雅黑' onclick=changeDepartment('"+departmentRegionCode+
             "','"+departmentName+"',"+departmentId+") />";
            cellContent.push(departmentChangeBtn);
            
          //  cellContent.push("<input type='text' style='width:200px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.department_name + "' />");
          //  cellContent.push("<div style='height:10px;'>" + data.rows[i].cell.department_category + "</div>");
            cellContent.push("<input type='text' style='width:200px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.department_remarks + "' />");
            var content = {
                cell: cellContent
            };
            rows.push(content);
        }
        newData = {
            total: data.total,
            page: data.page,
            rows: rows
        };
        return newData;
    }
}
